package com.cbtx.utils

import org.apache.commons.codec.binary.Base64
import java.io.*


/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/9 2:45 AM
 * desc   :
 */
object Base64Util {
    /**
     * 将对象进行base64
     * @param object
     */
    fun objectTo64Str(`object`: Any?): String? {
        var objBase64: String? = ""
        val baos = ByteArrayOutputStream()
        var oos: ObjectOutputStream? = null
        try {
            oos = ObjectOutputStream(baos)
            oos.writeObject(`object`)
            // 将对象的转为base64码
            objBase64 = String(
                Base64.encodeBase64(
                    baos
                        .toByteArray()
                )
            )
            oos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return objBase64
    }

    /**
     * 将SharePref中经过base64编码的对象读取出来
     *
     * @param objBase64
     * @return
     */
    fun base64ToObject(objBase64: String): Any? {
        // 对Base64格式的字符串进行解码
        val base64Bytes: ByteArray = Base64.decodeBase64(objBase64.toByteArray())
        val bais = ByteArrayInputStream(base64Bytes)
        val ois: ObjectInputStream
        var obj: Any? = null
        try {
            ois = ObjectInputStream(bais)
            obj = ois.readObject() as Any
            ois.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return obj
    }
}